<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="batch-update-dialog">
      <div class="select-hint">
        已选择 <strong>{{ selectedCount }}</strong> 项需求
      </div>
      <div class="select-label" v-if="type !== 'project-version'">请选择要设置的值：</div>
      
      <!-- 普通选择器 -->
      <el-select
        v-if="type === 'select'"
        v-model="selectedValue"
        :placeholder="placeholder"
        style="width: 100%"
        size="large"
        :filterable="options.length > 5"
        clearable
      >
        <el-option
          v-for="option in options"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      
      <!-- 用户选择器 -->
      <el-select
        v-else-if="type === 'user'"
        v-model="selectedValue"
        :placeholder="placeholder"
        style="width: 100%"
        size="large"
        :filterable="users.length > 5"
        clearable
      >
        <el-option
          v-for="user in users"
          :key="user.id"
          :label="user.name || user.username"
          :value="user.id"
        >
          <UserDisplay
            :user="user"
            :show-avatar="true"
            size="small"
          />
        </el-option>
      </el-select>
      
      <!-- 项目和版本选择器 -->
      <template v-else-if="type === 'project-version'">
        <div class="form-item">
          <div class="form-label">选择项目：</div>
          <el-select
            v-model="selectedProjectId"
            placeholder="请先选择项目"
            style="width: 100%"
            size="large"
            :filterable="(props.projects || []).length > 5"
            clearable
            @change="handleProjectChange"
          >
            <el-option
              v-for="project in (props.projects || [])"
              :key="project.value"
              :label="project.label"
              :value="project.value"
            />
          </el-select>
        </div>
        <div class="form-item">
          <div class="form-label">选择版本（可选）：</div>
          <el-select
            v-model="selectedVersionId"
            placeholder="请选择版本（可选）"
            style="width: 100%"
            size="large"
            :filterable="versions.length > 5"
            :disabled="!selectedProjectId"
            clearable
          >
            <el-option
              v-for="version in versions"
              :key="version.value"
              :label="version.label"
              :value="version.value"
            />
          </el-select>
        </div>
      </template>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleConfirm"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import UserDisplay from '@/components/ui/UserDisplay.vue'
import type { User } from '@/types/user'

interface Option {
  value: string
  label: string
}

interface Props {
  modelValue: boolean
  title: string
  placeholder?: string
  selectedCount: number
  type: 'select' | 'user' | 'project-version'
  options?: Option[]
  users?: User[]
  projects?: Option[]
  versions?: Option[]
  defaultValue?: string
  defaultProjectId?: string
  defaultVersionId?: string
  loading?: boolean
  onLoadVersions?: (projectId: string) => Promise<Option[]>
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', value: string | { projectId: string; versionId?: string }): void
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请选择',
  options: () => [],
  users: () => [],
  projects: () => [],
  versions: () => [],
  defaultValue: undefined,
  defaultProjectId: undefined,
  defaultVersionId: undefined,
  loading: false,
  onLoadVersions: undefined
})

const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const selectedValue = ref<string>('')
const selectedProjectId = ref<string>('')
const selectedVersionId = ref<string>('')
const versions = ref<Option[]>([])
const loadingVersions = ref(false)

// 加载版本列表
const loadVersions = async (projectId: string) => {
  if (!props.onLoadVersions || !projectId) {
    versions.value = []
    return
  }
  
  loadingVersions.value = true
  try {
    versions.value = await props.onLoadVersions(projectId)
  } catch (error) {
    console.error('加载版本列表失败:', error)
    versions.value = []
  } finally {
    loadingVersions.value = false
  }
}

// 处理项目变化
const handleProjectChange = (projectId: string | null) => {
  selectedVersionId.value = ''
  if (projectId) {
    loadVersions(projectId)
  } else {
    versions.value = []
  }
}

// 监听 defaultValue 变化，设置初始值
watch(() => props.defaultValue, (newVal) => {
  if (newVal !== undefined) {
    selectedValue.value = newVal
  } else if (props.type === 'select' && props.options.length > 0) {
    selectedValue.value = props.options[0]?.value || ''
  } else {
    selectedValue.value = ''
  }
}, { immediate: true })

// 监听项目默认值
watch(() => props.defaultProjectId, (newVal) => {
  if (props.type === 'project-version') {
    selectedProjectId.value = newVal || ''
    if (newVal) {
      loadVersions(newVal)
    } else {
      versions.value = []
    }
  }
}, { immediate: true })

// 监听版本默认值
watch(() => props.defaultVersionId, (newVal) => {
  if (props.type === 'project-version') {
    selectedVersionId.value = newVal || ''
  }
}, { immediate: true })

// 监听弹窗打开，重置选择
watch(visible, (newVal) => {
  if (newVal) {
    if (props.type === 'project-version') {
      selectedProjectId.value = props.defaultProjectId || ''
      selectedVersionId.value = props.defaultVersionId || ''
      versions.value = []
      if (selectedProjectId.value && props.onLoadVersions) {
        loadVersions(selectedProjectId.value)
      }
    } else {
      if (props.defaultValue !== undefined) {
        selectedValue.value = props.defaultValue
      } else if (props.type === 'select' && props.options.length > 0) {
        selectedValue.value = props.options[0]?.value || ''
      } else {
        selectedValue.value = ''
      }
    }
  } else {
    // 弹窗关闭时重置
    selectedValue.value = ''
    selectedProjectId.value = ''
    selectedVersionId.value = ''
    versions.value = []
  }
})

// 监听 type 变化，重置选择
watch(() => props.type, (newType) => {
  if (newType === 'project-version') {
    selectedValue.value = ''
    selectedProjectId.value = props.defaultProjectId || ''
    selectedVersionId.value = props.defaultVersionId || ''
    versions.value = []
    if (selectedProjectId.value && props.onLoadVersions) {
      loadVersions(selectedProjectId.value)
    }
  } else {
    selectedProjectId.value = ''
    selectedVersionId.value = ''
    versions.value = []
  }
})

const handleConfirm = () => {
  if (props.type === 'project-version') {
    if (!selectedProjectId.value) {
      ElMessage.warning('请选择项目')
      return
    }
    emit('confirm', {
      projectId: selectedProjectId.value,
      versionId: selectedVersionId.value || undefined
    })
  } else {
    if (!selectedValue.value) {
      ElMessage.warning('请选择一个选项')
      return
    }
    emit('confirm', selectedValue.value)
  }
}

const handleClose = () => {
  visible.value = false
  selectedValue.value = ''
  selectedProjectId.value = ''
  selectedVersionId.value = ''
  versions.value = []
}
</script>

<style scoped lang="scss">
.batch-update-dialog {
  .select-hint {
    margin-bottom: 16px;
    font-size: 14px;
    color: #606266;
    
    strong {
      color: #409eff;
      font-weight: 600;
    }
  }
  
  .select-label {
    margin-bottom: 12px;
    font-size: 14px;
    color: #303133;
    font-weight: 500;
  }
  
  .form-item {
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .form-label {
      margin-bottom: 8px;
      font-size: 14px;
      color: #303133;
      font-weight: 500;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

